package com.example.librarysystem.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ViewService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<String> getViewNames() {
        String sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS " +
                "WHERE TABLE_SCHEMA = 'bookmanager'";
        return jdbcTemplate.query(sql, (rs, rowNum) -> rs.getString("TABLE_NAME"));
    }

    public List<Map<String, Object>> queryView(String viewName) {
        String sql = "SELECT * FROM " + viewName;
        return jdbcTemplate.query(sql, (rs, rowNum) -> {
            Map<String, Object> row = new HashMap<>();
            int columnCount = rs.getMetaData().getColumnCount();
            for (int i = 1; i <= columnCount; i++) {
                row.put(rs.getMetaData().getColumnName(i), rs.getObject(i));
            }
            return row;
        });
    }
}